package com.jds.test.httpproxy.httpclient;

/**
 * Created by joyce on 2019/12/26.
 */

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * https://www.cnblogs.com/silyvin/p/12099743.html
 * Created by joyce on 2019/11/17.
 */

/**
 * 自己的https，需要忽略证书
 */
public class ProxySender {

    private static final String dir = "https://localhost:8080";

    public static void send(OriginHttp originHttp) {

        String method = originHttp.getMethod();
        String uri = originHttp.getUri();
        String url = new StringBuilder(dir).append(uri).toString();

        HttpUriRequest httpUriRequest = null;

        if("GET".equals(method)) {
            httpUriRequest = new HttpGet(url);
        } else if("POST".equals(method)) {
            httpUriRequest = new HttpPost(url);

            HttpPost httpPost = (HttpPost)httpUriRequest;
            try {
                String st = new String(originHttp.getBody());
                httpPost.setEntity(new StringEntity(st));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        Map<String, String> headers = originHttp.getHeaders();
        for(Map.Entry<String, String> entry : headers.entrySet()) {
            httpUriRequest.addHeader(entry.getKey(), entry.getValue());
        }
        httpUriRequest.addHeader("AUTH", "memories");
        httpUriRequest.addHeader("Cookie", "AUTH=memories");
        httpUriRequest.removeHeaders("Content-Length");
        httpUriRequest.removeHeaders("Origin");
        httpUriRequest.removeHeaders("Referer");
        httpUriRequest.removeHeaders("Host");
        httpUriRequest.addHeader("Origin", dir);
        httpUriRequest.addHeader("Referer", dir);
    //    httpUriRequest.addHeader("Host", dir);

        // 响应模型
        CloseableHttpClient httpClient = HttpClientFactory.createSSLClientDefault();
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpUriRequest);

            Map<String, String> map = new HashMap<>();
            Header [] headersRes = response.getAllHeaders();
            for(Header header : headersRes) {
                map.put(header.getName(), header.getValue());
            }

            int ret = response.getStatusLine().getStatusCode();

            HttpEntity responseEntity = response.getEntity();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            InputStream inputStream = responseEntity.getContent();
            if(inputStream != null) {
                byte [] bytes = new byte[1024];
                int i= 0;
                while ((i = inputStream.read(bytes)) != -1) {
                    byteArrayOutputStream.write(bytes, 0, i);
                }
            }

            System.out.println(new String(byteArrayOutputStream.toByteArray()));

            ResHttp resHttp = new ResHttp(ret, map, byteArrayOutputStream.toByteArray());
            ChannelFuture channelFuture = originHttp.getContext().writeAndFlush(resHttp);
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {

                    /**
                     * 短链接设置，当使用短链接时，不需要设置length或chunked
                     */
                //    future.channel().close();

                    if(!future.isSuccess()) {
                        future.cause().printStackTrace();
                        future.channel().close();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }



    }

}

